package thread;

/**
 * @author DBX
 * @effect
 * @date 2021/09/02/9:17
 */

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 聊天室客户端
 */
public class MyClient {
    private Socket socket;
    private String name;
    private boolean state=true;
    /**
     * 构造方法，用于初始化客户端
     */
    public MyClient(String ipaddr,int port,String name) {
        try {
            socket=new Socket(ipaddr,port);
            this.name=name;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 客户端开始工作的方法
     */
    public void start(){
        try{
            OutputStream out=socket.getOutputStream();
            OutputStreamWriter osw=new OutputStreamWriter(out,"utf-8");
            BufferedWriter bw=new BufferedWriter(osw);
            PrintWriter pw=new PrintWriter(bw,true);
            pw.println(name);//首次建立连接发送用户名字
            new Thread(new Runnable() {
                public void run() {
                    InputStreamReader isr= null;
                    try {
                        isr = new InputStreamReader(socket.getInputStream(),"utf-8");
                        BufferedReader br=new BufferedReader(isr);
                        String b;
                        while ((b=br.readLine())!=null){
                            System.out.println(b);
                        }
                    } catch (IOException e) {
                        System.out.println("退出群聊");
                    }
                    state=false;
                }
            }).start();
            Scanner in=new Scanner(System.in);
            while (state){ //向服务器发送消息
                String s=in.nextLine();
                if("exit".equals(s))
                    break;
                pw.println(s);
                //System.out.println("我:"+s);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        String ip="localhost";
        String ip2="176.225.131.228";
        String ip3="176.255.131.177";
        String ip4="121.5.157.155";
        new MyClient(ip4,8088,"欢喜").start();
    }
}